package com.chen.q2.JdbcInsert;

import com.chen.q2.Entity.TOrder;
import com.chen.q2.snowflakes.IdWorker;
import com.chen.q2.utils.PreparedStatementSqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;

/**
 * 单线程插入100W条数据，大概60秒左右
 */
@Component
public class JDBCInsert {
    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    private IdWorker idWorker = new IdWorker(11,1,0);

    public void executeOnMillionInsert() {
        Connection conn = null;
        PreparedStatement pst = null;
        String insertOrderSql = PreparedStatementSqlUtil.generateInsertPreparedStatementSql(TOrder.class);
        //String insertOrderDetailSql = PreparedStatementSqlUtil.generateInsertPreparedStatementSql(TOrderDetail.class);
        try {
            conn = dataSource.getConnection();
            conn.setAutoCommit(false);
            pst = conn.prepareStatement(insertOrderSql);
            TOrder order = TOrder.builder()
                    .createTime(new Date())
                    .build();

            for (int id=0;id<=100_0000;id++){
                order.setId(Long.valueOf(id));
                order.setOrderNo(String.valueOf(idWorker.nextId()));
                PreparedStatementSqlUtil.setPrepareStatementParams(pst, order);
                pst.addBatch();
                if(id%1_0000 == 0){//每1W行记录提交1次
                    pst.executeBatch();
                }
            }
            pst.executeBatch();
            conn.commit();

        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
                conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
